#include "edge.h"
#include "vertex.h"
#include "graph.h"

#include <QPainter>

class EdgePrivate
{
public:
	EdgePrivate(Graph *g) : graph(g), u(0), v(0) { }
	Graph *graph;
	QLineF line;
	QColor color;
	Vertex *u;
	Vertex *v;
};

Edge::Edge(Graph *parent)
	: QGraphicsItem()
	, d(new EdgePrivate(parent))
{
}

Edge::Edge(Graph *parent, Vertex* u, Vertex* v)
	: QGraphicsItem()
	, d(new EdgePrivate(parent))
{
	setU(u);
	setV(v);

}

QPainterPath Edge::shape() const
{
	QPainterPath path;
	if (d->line == QLineF())
		return path;
	path.moveTo(d->line.p1());
	path.lineTo(d->line.p2());
	return path;
}

QRectF Edge::boundingRect() const
{
	return shape().controlPointRect();
}

void Edge::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget)
{
	Q_UNUSED(option)
	Q_UNUSED(widget)
	if (d->line == QLineF())
		return;
	painter->drawLine(d->line);
}

void Edge::setLine(const QLineF &line)
{
	if (d->line == line)
		return;
	d->line = line;
	update();
}

QLineF Edge::line() const
{
	return d->line;
}

void Edge::setColor(const QColor &color)
{
	if (d->color == color)
		return;
	d->color = color;
	update();
}

QColor Edge::color() const
{
	return d->color;
}

void Edge::setU(Vertex *u)
{
	if (d->u == u)
		return;
	d->u = u;
	if (!(d->v)||!(d->u))
		return;
	QLineF line;
	line.setP1(d->u->scenePos());
	line.setP2(d->v->scenePos());
	setLine(line);
}

void Edge::setV(Vertex *v)
{
	if (d->v == v)
		return;
	d->v = v;
	if (!(d->v)||!(d->u))
		return;
	QLineF line;
	line.setP1(d->u->scenePos());
	line.setP2(d->v->scenePos());
	setLine(line);
}

Vertex *Edge::u() const
{
	return d->u;
}

Vertex *Edge::v() const
{
	return d->v;
}

double Edge::length() const
{
	return d->line.length();
}

void Edge::setParentGraph(Graph *g)
{
	d->graph = g;
}

Graph *Edge::parentGraph() const
{
	return d->graph;
}

// VirtualEdge
void VirtualEdge::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget)
{
	Q_UNUSED(painter)
	Q_UNUSED(option)
	Q_UNUSED(widget)
}

void VirtualEdge::setEdges(QList<Edge *>edges)
{
	m_edges = edges;
}

void VirtualEdge::addEdge(Edge *e)
{
	m_edges.append(e);
}

double VirtualEdge::length() const
{
	if(m_edges.empty())
		return 999999999;

	double result = 0.0;
	foreach (Edge *e, m_edges) {
		result += e->length();
	}
	return result;
}

void VirtualEdge::clearEdges()
{
	m_edges.clear();
}
